//
//  CartViewController.m
//  StandardizedProduct
//
//  Created by 宁宁 on 16/6/21.
//  Copyright © 2016年 ym. All rights reserved.
//

#import "CartViewController.h"

#import "CartFooterView.h"//页脚View
#import "CartHeaderView.h"//页眉View
#import "CartTableViewCell.h"//cell

#import "CartModel.h"//商品Model

#import "GoodsDetailViewController.h"//商品详情页

@interface CartViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

@end

@implementation CartViewController
{
    CartFooterView *_footerView;
    
    NSMutableArray *_dataArray;
    NSMutableArray *_selectedBoolArray;//商家选择bool
    NSMutableArray *_editBoolArray;

    NSMutableArray *_cellButtonArray;//cell选择按钮数组
    
    BOOL _isSelectedAll;//全选状态
    BOOL _isEditAll;//全编辑状态
}

 static NSString *const CartFooterViewID = @"CartFooterView";
 static NSString *const CartHeaderViewID = @"CartHeaderView";
 static NSString *const CartTableViewCellID = @"CartTableViewCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _isSelectedAll = NO;
    _isEditAll = NO;
    
    
    //设置导航栏
    [self setNav];
    
    //初始化数据源
    [self createDataArray];
    
    //设置tableView
    [self setTableView];
    
    //设置页脚
    [self setFooterView];
}


#pragma mark === 设置导航栏 ===
- (void)setNav{
    self.title = @"购物车";
    
    UIBarButtonItem *rightItem1 = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(edit:)];
    UIBarButtonItem *rightItem2 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"moreicon"] style:UIBarButtonItemStylePlain target:self action:@selector(more)];
    self.navigationItem.rightBarButtonItems = @[rightItem2, rightItem1];
}


#pragma mark === 初始化数据源 ===
- (void)createDataArray{
    _dataArray = [NSMutableArray array];
    _selectedBoolArray = [NSMutableArray array];
    _cellButtonArray = [NSMutableArray array];
    
    NSArray *arr = @[@[@"10000", @"200", @"3000"], @[@"2000", @"30"], @[@"30", @"4000"]];
    
    //购物车商品
    for (int i = 0; i < arr.count; i++) {
        NSMutableArray *modelArr = [NSMutableArray array];
        NSMutableArray *cellButtonArr = [NSMutableArray array];
        //商店商品
        for (int j = 0; j < [arr[i] count]; j++) {
            CartModel *model = [[CartModel alloc] init];
            model.price = arr[i][j];
            model.isSelected = NO;
            [modelArr addObject:model];
        }
        [_dataArray addObject:modelArr];
        //将空数组加入cellButtonArray
        [_cellButtonArray addObject:cellButtonArr];
    }
    
    for (int i = 0; i < _dataArray.count; i++) {
        [_selectedBoolArray addObject:[NSNumber numberWithBool:NO]];
        [_editBoolArray addObject:[NSNumber numberWithBool:NO]];
    }
}

#pragma mark === 注册TableView ===
- (void)setTableView{
    //注册页眉
    [self.tableView registerNib:[UINib nibWithNibName:@"CartHeaderView" bundle:nil] forCellReuseIdentifier:CartHeaderViewID];
    //注册自定义cell
    [self.tableView registerNib:[UINib nibWithNibName:@"CartTableViewCell" bundle:nil] forCellReuseIdentifier:CartTableViewCellID];
}

#pragma mark === 设置结算合计 页脚 ===
- (void)setFooterView{
    _footerView = [[CartFooterView alloc] initWithFrame:CGRectMake(0, HEIGHT - 105, WIDTH, 55)];
    [_footerView.chooseBtn addTarget:self action:@selector(chooseAll) forControlEvents:UIControlEventTouchUpInside];
    [_footerView.settlement addTarget:self action:@selector(settlement) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_footerView];
}



#pragma mark === TableViewDelegate ===
//section数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dataArray.count;
}
//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_dataArray[section] count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 90;
}
//页眉
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    CartHeaderView *headerView = [[[NSBundle mainBundle] loadNibNamed:@"CartHeaderView" owner:nil options:nil] lastObject];
    //选择
    headerView.chooseBtn.tag = 222200 + section;
    [headerView.chooseBtn addTarget:self action:@selector(chooseMerchantAll:) forControlEvents:UIControlEventTouchUpInside];
    if ([_selectedBoolArray[section] boolValue]) {
        headerView.chooseImage.image = [UIImage imageNamed:@"isSelected"];
        headerView.chooseImage.backgroundColor = APPCOLOR;
    }else{
        headerView.chooseImage.image = [UIImage imageNamed:@"unSelected"];
        headerView.chooseImage.backgroundColor = [UIColor clearColor];
    }
    //跳转商家
    headerView.merchant.tag = 322200 + section;
    [headerView.merchant addTarget:self action:@selector(linkToMerchant:) forControlEvents:UIControlEventTouchUpInside];
    headerView.merchantImage.backgroundColor = [UIColor yellowColor];
    
    headerView.edit.tag = 422200 + section;
    [headerView.edit addTarget:self action:@selector(editGoods:) forControlEvents:UIControlEventTouchUpInside];
    
    return headerView;
}
//页眉高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 45;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CartTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CartTableViewCellID];
    
    CartModel *model = _dataArray[indexPath.section][indexPath.row];
    
    cell.price.text = model.price;
    [cell.chooseButton addTarget:self action:@selector(cellSelected:) forControlEvents:UIControlEventTouchUpInside];
    
    NSMutableArray *buttonArray = _cellButtonArray[indexPath.section];
    if ([_cellButtonArray[indexPath.section] count] < indexPath.row + 1) {
        [buttonArray addObject:cell.chooseButton];
    }else [buttonArray replaceObjectAtIndex:indexPath.row withObject:cell.chooseButton];
    
    //页眉全选 或 cell被选
    if ([_selectedBoolArray[indexPath.section] boolValue] || model.isSelected == YES) {
        cell.chooseImage.image = [UIImage imageNamed:@"isSelected"];
        cell.chooseImage.backgroundColor = APPCOLOR;
    //页眉未全选 或 cell未被选
    }else{
        cell.chooseImage.image = [UIImage imageNamed:@"unSelected"];
        cell.chooseImage.backgroundColor = [UIColor clearColor];
    }
    
    
//    cell.goodsName.text = @"";
//    cell.goodsImage.image = [UIImage imageNamed:@""];
//    cell.goodsDetail.text = @"";
//    cell.colorAndSize.text = @"";
//    cell.price.text = @"";
//    cell.num.text = @"";
    
    
    
    cell.goodsImage.backgroundColor = [UIColor colorWithRed:VALUE green:VALUE blue:VALUE alpha:1];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
//商品选择
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"点击了第%ld个商家,第%ld件商品", indexPath.section, indexPath.row);
    GoodsDetailViewController *goodsDetail = [[GoodsDetailViewController alloc] init];
    goodsDetail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:goodsDetail animated:YES];
}

#pragma mark === cell选择 ===
- (void)cellSelected:(UIButton *)sender{
    for (int section = 0; section < _cellButtonArray.count; section++) {
        NSArray *arr = _cellButtonArray[section];
        for (int row = 0; row < arr.count; row++) {
            UIButton *button = arr[row];
            if (button == sender) {
                CartModel *model = _dataArray[section][row];
                model.isSelected = !model.isSelected;
                
                //1 判断当前是否商家商品全选
                [self AllGoods:section];
                
                //2 判断所有商家是否全选
                [self AllMerchant];
                
                //删除分段中的cellButtonArray
                NSMutableArray *arr = [NSMutableArray array];
                [_cellButtonArray replaceObjectAtIndex:section withObject:arr];
                //刷新分段
                [_tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationNone];
                
                //合计
                [self total];
                return;
            }
        }
    }
}

#pragma mark === 商家 页眉点击事件 ===
//该商店的商品全选
- (void)chooseMerchantAll:(UIButton *)sender{
    NSInteger index = sender.tag - 222200;
    //商家选择状态
    BOOL bo = [_selectedBoolArray[index] boolValue];
    [_selectedBoolArray replaceObjectAtIndex:index withObject:[NSNumber numberWithBool:!bo]];
    //对应商家所有商品选择状态
    for (int i = 0; i < [_dataArray[index] count]; i++) {
        CartModel *model = _dataArray[index][i];
        model.isSelected = !bo;
    }
    
    NSMutableArray *arr = [NSMutableArray array];
    [_cellButtonArray replaceObjectAtIndex:index withObject:arr];
    [_tableView reloadSections:[NSIndexSet indexSetWithIndex:index] withRowAnimation:UITableViewRowAnimationNone];
    
    //判断所有商家是否全选
    [self AllMerchant];
    
    //合计
    [self total];
}

//跳转到商店
- (void)linkToMerchant:(UIButton *)sender{
    NSInteger index = sender.tag - 322200;
    NSLog(@"跳转到第%ld家商店",index);
}

//编辑
- (void)editGoods:(UIButton *)sender{
//    NSInteger index = sender.tag - 422200;
//    BOOL bo = [_editBoolArray[index] boolValue];
//    [_editBoolArray replaceObjectAtIndex:index withObject:[NSNumber numberWithBool:!bo]];
//    
//    [_tableView reloadSections:[NSIndexSet indexSetWithIndex:index] withRowAnimation:UITableViewRowAnimationNone];
//    [_tableView setEditing:!bo animated:YES];
//    
//    if (!bo) {
//        [sender setTitle:@"完成" forState:UIControlStateNormal];
//    }else{
//        [sender setTitle:@"编辑" forState:UIControlStateNormal];
//    }
}
//重写父类编辑方法
- (void)setEditing:(BOOL)editing animated:(BOOL)animated{
    [super setEditing:editing animated:animated];
    [_tableView setEditing:YES animated:YES];
}
//TableViewDelegate编辑方法
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
//    if ([_editBoolArray[indexPath.section] boolValue]) {
//        return UITableViewCellEditingStyleDelete;
//    }else return UITableViewCellEditingStyleNone;
    return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [_dataArray[indexPath.section] removeObjectAtIndex:indexPath.row];
        
        [_tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
        [self total];
        
        if ([_dataArray[indexPath.section] count] == 0) {
            [_dataArray removeObjectAtIndex:indexPath.section];
            [_editBoolArray removeObjectAtIndex:indexPath.section];
            [_selectedBoolArray removeObjectAtIndex:indexPath.section];
            [_cellButtonArray removeObjectAtIndex:indexPath.section];
            [_tableView reloadData];
        }
    }
}

#pragma mark === 全选结算 页脚点击事件 ===
//全选
- (void)chooseAll{
    _isSelectedAll = !_isSelectedAll;
    //1 全选
    if (_isSelectedAll) {
        _footerView.chooseImage.image = [UIImage imageNamed:@"isSelected"];
        _footerView.chooseImage.backgroundColor = APPCOLOR;
        //所有商家全选
        for (int i = 0 ; i < _selectedBoolArray.count; i++) {
            [_selectedBoolArray replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:YES]];
            //所有商品全选
            for (int j = 0; j < [_dataArray[i] count]; j++) {
                CartModel *model = _dataArray[i][j];
                model.isSelected = YES;
            }
        }
        
    //2 取消全选
    }else{
        _footerView.chooseImage.image = [UIImage imageNamed:@"unSelected"];
        _footerView.chooseImage.backgroundColor = [UIColor clearColor];
        //所有商家取消全选
        for (int i = 0 ; i < _selectedBoolArray.count; i++) {
            [_selectedBoolArray replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:NO]];
            //所有商品取消全选
            for (int j = 0; j < [_dataArray[i] count]; j++) {
                CartModel *model = _dataArray[i][j];
                model.isSelected = NO;
            }
        }
    }
    //刷新TableView
    [_tableView reloadData];
    
    //合计
    [self total];
    
}
//判断商家的所有商品是否全选
- (void)AllGoods:(NSInteger)section{
    //1 判断当前是否商家商品全选
    int flag = 0;
    for (int i = 0; i < [_dataArray[section] count]; i++) {
        CartModel *model = _dataArray[section][i];
        if (model.isSelected == NO) {
            flag++;
        }
    }
    //当前商家商品全选
    if (flag == 0) {
        [_selectedBoolArray replaceObjectAtIndex:section withObject:[NSNumber numberWithBool:YES]];
        //当前商家商品未全选
    }else [_selectedBoolArray replaceObjectAtIndex:section withObject:[NSNumber numberWithBool:NO]];
}
//判断所有商家是否全选
- (void)AllMerchant{
    //判断当前所有商家是否全选
    int flag = 0;
    for (NSNumber *selected in _selectedBoolArray) {
        if (![selected boolValue]) {
            flag++;
        }
    }
    //所有商家全选
    if (flag == 0) {
        _isSelectedAll = YES;
        _footerView.chooseImage.image = [UIImage imageNamed:@"isSelected"];
        _footerView.chooseImage.backgroundColor = APPCOLOR;
        //所有商家未全选
    }else{
        _isSelectedAll = NO;
        _footerView.chooseImage.image = [UIImage imageNamed:@"unSelected"];
        _footerView.chooseImage.backgroundColor = [UIColor clearColor];
    }

}

#pragma MARK === 合计 ===
- (void)total{
    float totalMoney = 0;
    for (int i = 0; i < _dataArray.count; i++) {
        for (CartModel *model in _dataArray[i]) {
            if (model.isSelected) {
                totalMoney += [model.price floatValue];
            }
        }
    }
    _footerView.total.text = [NSString stringWithFormat:@"合计: ¥%.2f",totalMoney];
}
//结算
- (void)settlement{
    NSLog(@"结算");
}



#pragma mark === 导航栏Item点击事件 ===
//编辑
- (void)edit:(UIBarButtonItem *)item{
    _isEditAll = !_isEditAll;
    [_tableView setEditing:_isEditAll animated:YES];
    if (_isEditAll) {
        [item setTitle:@"完成"];
        for (int i = 0; i < _editBoolArray.count; i++) {
            [_editBoolArray replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:YES]];
        }
    }else{
        [item setTitle:@"编辑"];
        for (int i = 0; i < _editBoolArray.count; i++) {
            [_editBoolArray replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:NO]];
        }
    }
}
//更多
- (void)more{
    NSLog(@"更多");
}



- (UITableView *)tableView{
    if (!_tableView) {
        _tableView= [[UITableView alloc]initWithFrame:CGRectMake(0,0, WIDTH, HEIGHT - 105)style:UITableViewStyleGrouped];
        _tableView.sectionFooterHeight = 10.0;
        _tableView.sectionHeaderHeight = 0;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;//去掉滑动竖条
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
@end
